package com.shanjupay.paymentagent.message;

import com.alibaba.fastjson.JSON;
import com.shanjupay.paymentagent.api.PayChannelAgentService;
import com.shanjupay.paymentagent.api.conf.AliConfigParam;
import com.shanjupay.paymentagent.api.dto.PaymentResponseDTO;
import com.shanjupay.paymentagent.api.dto.TradeStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @className: PayConsumer
 * @Description: TODO
 * @author: Huangjianyun
 * @date: 2021/10/28 12:23
 */
@Component
@RocketMQMessageListener(topic = "TP_PAYMENT_ORDER",consumerGroup = "CID_PAYMENT_CONSUMER")
@Slf4j
public class PayConsumer implements RocketMQListener<MessageExt> {


    @Autowired
    PayChannelAgentService payChannelAgentService;
    @Autowired
    PayProducer payProducer;
    //监听消息，进行消费消息
    @Override
    public void onMessage(MessageExt messageExt) {
        //从messageExt中获取消息
        byte[] body = messageExt.getBody();
        //获取的消息字节数组转化成json串
        String jsonString = new String(body);
        log.info("支付渠道代理服务接收到查询订单的消息：{}", JSON.toJSONString(jsonString));
        //将json消息进行转化成消息对象
        PaymentResponseDTO paymentResponseDTO = JSON.parseObject(jsonString, PaymentResponseDTO.class);
        //从消息对象获取订单号 支付渠道参数字符串
        String outTradeNo = paymentResponseDTO.getOutTradeNo();

        String params =String.valueOf(paymentResponseDTO.getContent());
        //将json字符串进行转化成对象
        AliConfigParam aliConfigParam = JSON.parseObject(params, AliConfigParam.class);
        PaymentResponseDTO responseDTO = null;
        //这里进行判断进行两次判断 是支付宝还是微信调用各自的接口获取各自的订单状态
        if("ALIPAY_WAP".equals(paymentResponseDTO.getMsg())){
            //调用支付宝的接口获取订单状态
            responseDTO = payChannelAgentService.queryPayOrderByAli(aliConfigParam, outTradeNo);
        }else if("WX_JSAPI".equals(paymentResponseDTO.getMsg())){
            //调用微信的查询订单的结果获取订单状态
        }
        //如果没有获取到订单结果抛出异常重新的消费消息
        if(responseDTO == null || TradeStatus.UNKNOWN.equals(responseDTO.getTradeState()) ||
        TradeStatus.USERPAYING.equals(responseDTO.getTradeState())
        ){
            //直接抛出异常重新进行消费
            throw new RuntimeException("订单状态未知，请重新消费");
        }

        //如果重试的次数达到一次数量，不要再重试消费，将消息记录到数据库，由单独的程序或人工进行处理
        //将订单状态再次发送给rocketMQ,
        payProducer.payResultNotice(responseDTO);
    }
}
